<template>
  <div class="search-container">
    <!-- 头部 -->
    <div class="search-header">
      <el-button 
        icon="ArrowLeft" 
        circle 
        @click="goBack"
        class="back-btn"
      />
      <div class="search-input-wrapper">
        <el-input
          v-model="searchQuery"
          placeholder="搜索演出、艺人、设施..."
          prefix-icon="Search"
          clearable
          @input="handleSearch"
          @keyup.enter="performSearch"
          ref="searchInputRef"
        />
      </div>
    </div>

    <!-- 搜索历史 -->
    <div v-if="!searchQuery && searchHistory.length > 0" class="search-history">
      <div class="history-header">
        <h3>搜索历史</h3>
        <el-button type="text" @click="clearHistory">清空</el-button>
      </div>
      <div class="history-list">
        <div 
          v-for="item in searchHistory" 
          :key="item"
          class="history-item"
          @click="searchFromHistory(item)"
        >
          <el-icon><Clock /></el-icon>
          <span>{{ item }}</span>
          <el-icon class="delete-icon" @click.stop="removeFromHistory(item)">
            <Close />
          </el-icon>
        </div>
      </div>
    </div>

    <!-- 热门搜索 -->
    <div v-if="!searchQuery" class="hot-searches">
      <h3>热门搜索</h3>
      <div class="hot-tags">
        <el-tag 
          v-for="tag in hotSearches" 
          :key="tag"
          @click="searchFromHistory(tag)"
          class="hot-tag"
        >
          {{ tag }}
        </el-tag>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchQuery && !loading" class="search-results">
      <div class="results-header">
        <h3>搜索结果 ({{ totalResults }})</h3>
        <el-select v-model="activeCategory" @change="handleCategoryChange">
          <el-option label="全部" value="all" />
          <el-option label="演出" value="performance" />
          <el-option label="艺人" value="artist" />
          <el-option label="设施" value="facility" />
        </el-select>
      </div>

      <!-- 演出结果 -->
      <div v-if="activeCategory === 'all' || activeCategory === 'performance'" class="result-section">
        <h4 v-if="activeCategory === 'all'">演出</h4>
        <div class="result-list">
          <div 
            v-for="item in performanceResults" 
            :key="item.id"
            class="result-item"
            @click="viewPerformance(item)"
          >
            <div class="result-icon">
              <el-icon size="20" color="#667eea"><VideoPlay /></el-icon>
            </div>
            <div class="result-content">
              <h5>{{ item.title }}</h5>
              <p>{{ item.artist?.name }} · {{ item.venue }}</p>
            </div>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>
      </div>

      <!-- 艺人结果 -->
      <div v-if="activeCategory === 'all' || activeCategory === 'artist'" class="result-section">
        <h4 v-if="activeCategory === 'all'">艺人</h4>
        <div class="result-list">
          <div 
            v-for="item in artistResults" 
            :key="item.id"
            class="result-item"
            @click="viewArtist(item)"
          >
            <div class="result-icon">
              <el-icon size="20" color="#ff6b6b"><User /></el-icon>
            </div>
            <div class="result-content">
              <h5>{{ item.name }}</h5>
              <p>{{ item.genre }} · {{ item.country }}</p>
            </div>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>
      </div>

      <!-- 设施结果 -->
      <div v-if="activeCategory === 'all' || activeCategory === 'facility'" class="result-section">
        <h4 v-if="activeCategory === 'all'">设施</h4>
        <div class="result-list">
          <div 
            v-for="item in facilityResults" 
            :key="item.id"
            class="result-item"
            @click="viewFacility(item)"
          >
            <div class="result-icon">
              <el-icon size="20" color="#4ecdc4"><Location /></el-icon>
            </div>
            <div class="result-content">
              <h5>{{ item.name }}</h5>
              <p>{{ item.description }} · {{ item.floor }}</p>
            </div>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>
      </div>

      <!-- 空结果 -->
      <div v-if="totalResults === 0" class="empty-results">
        <el-icon size="60" color="#ccc"><Search /></el-icon>
        <p>未找到相关结果</p>
        <p class="suggestion">试试其他关键词</p>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-icon class="is-loading" size="24"><Loading /></el-icon>
      <p>搜索中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { searchPerformances } from '@/api/performance'
import { searchArtists } from '@/api/artist'
import { searchFacilities } from '@/api/facility'
import type { Performance, Artist, Facility } from '@/types'

// 响应式数据
const searchQuery = ref('')
const loading = ref(false)
const activeCategory = ref('all')
const searchInputRef = ref<HTMLElement>()

// 搜索结果
const performanceResults = ref<Performance[]>([])
const artistResults = ref<Artist[]>([])
const facilityResults = ref<Facility[]>([])

// 搜索历史
const searchHistory = ref<string[]>([])

// 热门搜索
const hotSearches = ref([
  '流行音乐', '摇滚', '电子音乐', '民谣', '洗手间', '餐饮区', '医疗点'
])

// 计算属性
const totalResults = computed(() => {
  return performanceResults.value.length + 
         artistResults.value.length + 
         facilityResults.value.length
})

// 获取路由
const router = useRouter()

// 返回上一页
const goBack = () => {
  router.back()
}

// 处理搜索输入
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    performSearch()
  }
}

// 执行搜索
const performSearch = async () => {
  if (!searchQuery.value.trim()) return
  
  loading.value = true
  
  try {
    // 并行搜索不同类型
    const [performanceRes, artistRes, facilityRes] = await Promise.all([
      searchPerformances(searchQuery.value),
      searchArtists(searchQuery.value),
      searchFacilities({ q: searchQuery.value })
    ])
    
    performanceResults.value = performanceRes.data
    artistResults.value = artistRes.data
    facilityResults.value = facilityRes.data
    
    // 添加到搜索历史
    addToHistory(searchQuery.value)
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 处理分类切换
const handleCategoryChange = () => {
  // 分类切换逻辑已在模板中处理
}

// 从历史记录搜索
const searchFromHistory = (query: string) => {
  searchQuery.value = query
  performSearch()
}

// 添加到搜索历史
const addToHistory = (query: string) => {
  if (!searchHistory.value.includes(query)) {
    searchHistory.value.unshift(query)
    if (searchHistory.value.length > 10) {
      searchHistory.value.pop()
    }
    // 保存到本地存储
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
}

// 从历史记录中移除
const removeFromHistory = (query: string) => {
  const index = searchHistory.value.indexOf(query)
  if (index > -1) {
    searchHistory.value.splice(index, 1)
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
}

// 清空搜索历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

// 查看演出详情
const viewPerformance = (performance: Performance) => {
  router.push(`/performances/${performance.id}`)
}

// 查看艺人详情
const viewArtist = (artist: Artist) => {
  router.push(`/artists/${artist.id}`)
}

// 查看设施详情
const viewFacility = (facility: Facility) => {
  ElMessage.info(`查看${facility.name}详情`)
}

// 页面挂载时执行
onMounted(() => {
  // 加载搜索历史
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
  
  // 聚焦搜索框
  nextTick(() => {
    searchInputRef.value?.focus()
  })
})
</script>

<style lang="scss" scoped>
.search-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 20px;
}

.search-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  flex-shrink: 0;
}

.search-input-wrapper {
  flex: 1;
}

.search-history {
  background: white;
  margin: 10px 20px;
  border-radius: 15px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  
  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0;
  }
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  
  &:hover {
    background: #f5f5f5;
  }
  
  span {
    flex: 1;
    color: #666;
  }
  
  .delete-icon {
    color: #999;
    cursor: pointer;
    
    &:hover {
      color: #ff6b6b;
    }
  }
}

.hot-searches {
  background: white;
  margin: 10px 20px;
  border-radius: 15px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 15px 0;
  }
}

.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.hot-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
  }
}

.search-results {
  padding: 0 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0;
  }
}

.result-section {
  margin-bottom: 30px;
  
  h4 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 15px 0;
  }
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-item {
  background: white;
  padding: 15px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
  }
}

.result-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(102, 126, 234, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.result-content {
  flex: 1;
  
  h5 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 5px 0;
  }
  
  p {
    font-size: 14px;
    color: #666;
    margin: 0;
  }
}

.arrow-icon {
  color: #999;
  font-size: 20px;
}

.empty-results {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  
  p {
    margin: 15px 0 0 0;
    font-size: 16px;
    
    &.suggestion {
      font-size: 14px;
      color: #666;
    }
  }
}

.loading-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  
  p {
    margin: 15px 0 0 0;
    font-size: 16px;
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  .search-header {
    padding: 12px 15px;
  }
  
  .search-history,
  .hot-searches {
    margin: 10px 15px;
    padding: 15px;
  }
  
  .search-results {
    padding: 0 15px;
  }
  
  .result-item {
    padding: 12px;
  }
  
  .result-icon {
    width: 35px;
    height: 35px;
  }
  
  .result-content {
    h5 {
      font-size: 14px;
    }
    
    p {
      font-size: 12px;
    }
  }
}
</style> 